//
//  CZUserAccountViewModel.swift
//  CZWeibo
//
//  Created by 周振兰 on 16/5/14.
//  Copyright © 2016年 周振兰. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {
//单例
    static let shareIntance :CZUserAccountViewModel = CZUserAccountViewModel()
    //账号归档与解档的路径
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
        /// 账号,全局只要拿到单例就可以访问,别人在任何都可以访问账号
    var userAccount : CZUserAccount?
    ///用户是否登录的属性
    var isUserLogin : Bool
        {
        get
        {
            return userAccount != nil  // 账号!=nil就表示登录了
        }
        
    }
    override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    
    func loadAcessToken(code:String ,callback:(error:NSError?)->())
    {
        let urlString = "oauth2/access_token"
        
        //参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri": redirect_uri
        ]
        
        // 发送POST请求获取AccessToken
        // 如果urlString里面开头是http或https就直接使用这个urlString,如果不是以http或https开头AFN会帮我们拼接baseURL
        
        CZNetworkTool.shareaIntance.request(RequestMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
            CZPrint(items: "获取AccessToken成功: \(responseObject)")
            if let result = responseObject as?[String : AnyObject]
            {
                //字典转模型
                self.userAccount = CZUserAccount(dict: result)
               
                
                //保存路径
                
                CZPrint(items:  "\(self.userAccountPath)")
                //调用归档的方法，将模型保存到沙盒中
                
                self.saveUserAccount()
                
                //告诉控制器，模型保存完成了
                callback(error: nil )
            } else
            {
                CZPrint(items: "返回字典失败")
            }
            
            
            }, failure: { (task, error) -> Void in callback(error: error)
                CZPrint(items: "失败了: \(error)")
        })
    }
    
    
      //保存账号到沙盒中
    private func saveUserAccount ()
    {
        
        if let account = userAccount
        {
            NSKeyedArchiver.archiveRootObject(account, toFile: self.userAccountPath)
        }
    }
    //解档账号
    func loadUserAccount() -> CZUserAccount?
    {
        let userAccount1 = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? CZUserAccount
        
        CZPrint(items: "\(userAccount1)")
        CZPrint(items: "\(self.userAccountPath)")
        
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? CZUserAccount
        {
            
            if userAccount.erpiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending
            {
                CZPrint(items: "没有过期")
                return userAccount
            }else
            {
                return nil
            }
        }else
        {
            return nil
        }
    }
   
    //MARK: - 获取用户名称和头像信息
    func loadUserInfo(loadUserInfoCallback:(error:NSError?)->())
    {
        guard let access_token = userAccount?.access_token else
        {
            //能进来里面说明access_token 没有值
            CZPrint(items: "access_token 没有值")
            return
        }
        
        guard let uid = userAccount?.uid else
        {
            return
        }
        let urlString = "2/users/show.json"
        //参数
        let parameters = [
            "access_token":access_token,
            "uid":uid
        ]
        //发送请求
        CZNetworkTool.shareaIntance.request(RequestMethod.GET, URLString:urlString , parameters: parameters, success: { (_, responseObject) -> Void in
            
            if let result = responseObject as? [String:NSObject]
            {
                CZPrint(items: "result的内容\(result)")
                //只需要用户的名称和头像地址    因为获取到的数据是字典所以需要转换成string类型
                let screen_name  = result["screen_name"]as! String
                let avatar_large = result["avatar_large"]as! String
                //赋值到当前账号的模型中
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                
                //将userAccount保存在沙盒中
                self.saveUserAccount()
                //通过欢迎界面显示信息，通过闭包来回调
                loadUserInfoCallback(error: nil )
                
            }
            
            }) { (_, error) -> Void in
                CZPrint(items: "获取用户信息出错了")
                loadUserInfoCallback(error:error)
        }
    }
}


